package com.heima.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vos.LoginVo;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.BCrypt;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {

    /**
     * 登录接口
     *   二合一，用户登录也是有游客登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.判断dto中是否存在手机号和密码
        if (StrUtil.isBlank(dto.getPassword())&&StrUtil.isBlank(dto.getPhone())){
            //不存在,是游客登录使用0生成jwt返回
            String token = AppJwtUtil.getToken(0L);
            Map<String,Object> user = new HashMap<>();
            user.put("id", 0);
            user.put("name", "");
            user.put("phone", "");
            LoginVo loginVo = LoginVo.of(user, token);

            return ResponseResult.okResult(loginVo);
        }
        //2.存在根据手机号查看用户是否存在
        ApUser apUser = this.lambdaQuery().eq(ApUser::getPhone, dto.getPhone()).one();
        if (apUser==null){
            throw new RuntimeException("用户名或密码错误");
        }

        //3.查看密码是否正确
        if (!BCrypt.checkpw(dto.getPassword(), apUser.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }

        //4.生成jwt返回
        String token = AppJwtUtil.getToken(Integer.toUnsignedLong(apUser.getId()));
        Map<String,Object> user = new HashMap<>();
        user.put("id", apUser.getId());
        user.put("name", apUser.getName());
        user.put("phone", apUser.getPhone());
        LoginVo loginVo = LoginVo.of(user, token);

        return ResponseResult.okResult(loginVo);
    }

    /**
     * 根据用户id获取用户实体
     *
     * @param userId
     * @return
     */
    @Override
    public ResponseResult<ApUser>findUserById(Integer userId) {
        ApUser apUser = getById(userId);
        return ResponseResult.okResult(apUser);
    }
}
